package at.irian.jsfatwork.dao.jpa;

import at.irian.jsfatwork.dao.CategoryDao;
import at.irian.jsfatwork.domain.Category;

import javax.inject.Named;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Named("categoryDao")
@Singleton
public class JpaCategoryDao implements CategoryDao {

    @PersistenceContext
    private EntityManager em;

    public Category createNew() {
        return new Category();
    }

    public void persist(Category category) {
        em.persist(category);
    }

    @SuppressWarnings({"unchecked"})
    public List<Category> findAll() {
        return em.createQuery("select c from Category c order by c.name asc").getResultList();
    }

    public Category findById(long id) {
        return em.find(Category.class, id);
    }

    public void delete(Category category) {
        em.remove(category);
    }

}
